﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Modbus.Device;

namespace WindowsFormsApp1
{
    
    internal class TcpModbusClient
    {
        TcpClient tcpClient = null;
        IModbusMaster master = null;
        public TcpModbusClient()
        {

        }
        public bool Connect(String ipAdress,int port)
        {
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(ipAdress, port);//连接到主机
                master = ModbusIpMaster.CreateIp(tcpClient);//Ip 主站
                master.Transport.ReadTimeout = 1000;//读超时
                master.Transport.WriteTimeout = 1000;//写超时
                master.Transport.Retries = 3;//尝试重复连接次数
                master.Transport.WaitToRetryMilliseconds = 200;//尝试重复连接间隔
                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show($"Error during connnect: {ex.Message}");
                return false;
            }
            
        }

        public void Disconnect()
        {
            master.Dispose();
            //logAction("Disconnected from server.");
        }
    }
    
}
